package com.example.reggie.controller;

import com.example.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author 23333
 */
@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController extends BaseController {
    /**
     * 获取配置文件的配置图片路径
     */
    @Value("${reggie.imgPath}")
    private String imgPath;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        //file是一个临时文件，需要转存到指定位置，否则本次请求完成后临时文件会删除
        log.info(file.toString());
        //获取上传的文件原始文件名
        String originalFilename = file.getOriginalFilename();
        //截取文件的扩展名
        String suffix = null;
        if (originalFilename != null) {
            suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        //随机文件名32位不重复文件名
        UUID uuid = UUID.randomUUID();
        //拼接新的文件名
        String fileName = uuid + suffix;
        //创建目录对象
        File dir = new File(imgPath);
        //判断目录是否存在，如果不存在，则新建目录
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //将上传的文件转移到指定的目录中
        try {
            file.transferTo(new File(imgPath, fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //返回文件名
        return R.success(fileName);
    }

    /**
     * 文件下载
     * @param name
     * @throws IOException
     */
    @GetMapping("/download")
    public void download(String name) throws IOException {
        FileInputStream fileInputStream = null;
        ServletOutputStream outputStream = null;
        try {
            //输入流，通过输入流读取文件内容
            fileInputStream = new FileInputStream(new File(imgPath + name));
            //输出流，通过输出流将文件写回浏览器
            outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");

            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //关闭资源
            if (fileInputStream != null) {
                fileInputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }
}
